<?php

class Sub_goods_model extends CI_Model
{

	private $table;
	//主货品货号
	private $m_number;
	public $error;

	function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');
		$this->test_database->test();
		//载入核心类
		$this->load->database($this->test_database->get_db());
		//载入库文件
		$this->load->library('form_validation');
		$this->load->library('session');
		//载入辅助类
		//$this->load->helper('cookie');
		//载入本地语言文件
		$this->lang->load('form_validation','chinese');
		//初始化参数
		$this->table = 'sub_goods';		//设置数据库表明
		$this->TABLE = @$this->table;	//$this->table的别名
	}

	function create($mid, $del_opt)
	{
		$this->load->model('Main_goods_model');
		$main_goods = array();
		$v = array();

		$v['main_goods_id'] = $this->input->post('main_goods_id');
		//判断主货品是否存在
		if ($main_goods = $this->Main_goods_model->getOne($v['main_goods_id']))
		{
			$this->m_number = $main_goods['number'];
		}
		else
		{
			$this->error = '错误：不存在主货品！';
			return false;
		}
		//$this->form_validation->set_rules('number', '货号', 'trim|required|min_length[2]|max_length[20]|xss_clean');
		$this->form_validation->set_rules('attribute', '属性', 'trim|required|min_length[2]|max_length[10]|unique[Sub_goods_model,attribute]|xss_clean');
		$this->form_validation->set_rules('search_code', '搜索代码', 'trim|required|min_length[2]|max_length[10]|alpha_dash|xss_clean');
		$this->form_validation->set_rules('supplier_ids', '供应商', 'trim|required|is_supplier|xss_clean');
		if ($this->form_validation->run())
		{
			$v['number'] = $this->m_number;
			$v['attribute'] = $this->input->post('attribute');
			$v['search_code'] = $this->input->post('search_code');
			$v['stock'] = 0;
			$v['order'] = 1;
			$v['create_date'] = time();
			$v['update_date'] = $v['create_date'];
			$v['del_flg'] = $del_opt;
			$this->db->insert($this->table, $v);
			return true;
		}
		return false;
	}

	public function update()
	{
		//$this->form_validation->set_rules('number', '货号', 'trim|required|min_length[2]|max_length[20]|unique[Sub_goods_model,number]|xss_clean');
		$this->form_validation->set_rules('attribute', '属性', 'trim|required|min_length[2]|max_length[10]|unique[Sub_goods_model,attribute,self]|xss_clean');
		$this->form_validation->set_rules('search_code', '搜索代码', 'trim|required|min_length[2]|max_length[10]|alpha_dash|xss_clean');
		//如果没有添加“供应商”则不校验
		if('' != $this->input->post('supplier_ids'))
		{
			$this->form_validation->set_rules('supplier_ids', '供应商', 'trim|required|is_supplier|xss_clean');
		}

		if ($this->form_validation->run())
		{
			$mid = $this->input->post('main_goods_id');
			$sid = $this->input->post('sub_goods_id');
			$v['attribute'] = $this->input->post('attribute');
			$v['search_code'] = $this->input->post('search_code');
			$v['update_date'] = time();
			$this->db->where('main_goods_id', $mid);
			$this->db->where('sub_goods_id', $sid);
			$this->db->update($this->table, $v);
			return true;
		}
		return false;
	}

	public function getOne($id)
	{
		$this->db->where('sub_goods_id', $id);
		$query = $this->db->get($this->table, 1);
		if ($query->num_rows() > 0)
		{
			return $query->row_array();
		}
		return false;
	}

	//getOne方法的别名
	public function get_one($sub_goods_id)
	{
		return $this->getOne($sub_goods_id);
	}

	function del($goods_id, $main = false)
	{
		$data = array('del_flg' => 1);
		if ($main)
		{
			$this->db->where('main_goods_id', $goods_id);
			$this->db->update($this->table, $data);
			return true;
		}
		else
		{
			$this->db->where('sub_goods_id', $goods_id);
			$this->db->update($this->table, $data);
			return true;
		}
		return false;
	}

	public function recover($goods_id, $main = false)
	{
		$data = array('del_flg' => 0);
		if ($main)
		{
			$this->db->where('main_goods_id', $goods_id);
			$this->db->update($this->table, $data);
			return true;
		}
		else
		{
			$this->db->where('sub_goods_id', $goods_id);
			$this->db->update($this->table, $data);
			return true;
		}
		return false;
	}

	public function search($type, $text, $group=FALSE)
	{
		$this->load->Model('Main_goods_model');
		if ('sn' == $type)
		{
			$this->db->like('number', $text);
		}
		else if ('ss' == $type)
		{
			$this->db->like('search_code', $text);
		}
		$query = $this->db->get($this->table);
		$sub_goods = $query->result();
		if ($group)
		{
			$sub_goods = $this->format_result($sub_goods, 'GROUP');
		}
		else
		{
			foreach ($sub_goods as $k=>$d)
			{
				$main_goods = $this->Main_goods_model->getOne($d->main_goods_id);
				$sub_goods[$k]->tb_info = $main_goods['taobao_info'];
			}
		}
		//var_dump($sub_goods);
		return $sub_goods;
	}

	//获得子货品
	public function getGoods($mid = false, $del_flg = 2)
	{
		if (!$mid)
		{
			$mid = $this->input->post('mid');
		}
		if (2 != $del_flg)
		{
			$this->db->where('del_flg', $del_flg);
		}
		$query = $this->db->get_where($this->table, array('main_goods_id'=>$mid));
		return $query->result();
	}

	//通过主货物ID获得对应子货物
	public function get_goods_by($get_type, $ids, $select=FALSE)
	{
		switch ($get_type) {
			case 'main_goods_id':
			case 'sub_goods_id':
				if (is_array($ids))
				{
					$this->db->where_in($get_type, $ids);
				}
				else
				{
					$this->db->where($get_type, $ids);
				}
				break;
			
			default:
				return FALSE;
		}
		if ($select)
		{
			$this->db->select($select);
		}
		if ($query = $this->db->get($this->TABLE))
		{
			return $query->result_array();
		}
		else
		{
			$this->error = 'SYS_ERR|SQL';
			return FALSE;
		}
	}

	//For ../libraris/MY_Form_validation.php
	//同一主货品下不能有相同值
	public function unique($value, $col=false, $self=false)
	{
		if ('number' == $col)
		{
			$value = $this->m_number . '-' . $value;
		}
		$this->db->where('main_goods_id', $this->input->post('main_goods_id'));
		$this->db->where($col, $value);
		if ($self)
		{
			$this->db->where('sub_goods_id !=', $this->input->post('sub_goods_id'));
		}
		$query = $this->db->get($this->table, 1);
		if ($query->num_rows() > 0)
		{
			return false;
		}
		return true;
	}

	//Return Array, key value is the sub_goods_id
	public function get_some($sub_goods_ids=array(), $order_by=false, $get_detail=false)
	{
		$this->load->model('Main_goods_model');

		$main_goodies = array();
		$main_goods_ids = array();
		$data = array();

		if (empty($sub_goods_ids))
		{
			$sub_goods_ids = $this->input->post('sub_goods_ids');
			if ($sub_goods_ids)
			{
				$this->db->where_in('sub_goods_id', $sub_goods_ids);
			}
		}
		else
		{
			$this->db->where_in('sub_goods_id', $sub_goods_ids);
		}
		if ($order_by)
		{
			$this->db->order_by($order_by);
		}
		//执行SQL
		$query = $this->db->get($this->table);
		if ($query->num_rows() > 0)
		{
			foreach ($query->result() as $g)
			{
				if (!$get_detail)
				{
					$data[$g->sub_goods_id] = $g;
				}
				else
				{
					$data[$g->sub_goods_id] = $g;
					if (!in_array($g->main_goods_id, $main_goods_ids))
					{
						//可优化
						$main_goodies[$g->main_goods_id] = $this->Main_goods_model->getOne($g->main_goods_id);
					}
					$data[$g->sub_goods_id] = array_merge(get_object_vars($data[$g->sub_goods_id]), $main_goodies[$g->main_goods_id]);
				}
			}
			return $data;
		}
		else
		{
			$this->error = '存在无效的子货品';
			return false;
		}
	}

	//获得所有的货物信息
	public function get_all()
	{
		return $this->db->get($this->table)->result();
	}

	//获得货物的各种信息
	public function get_goods_info($sub_goods_id)
	{
		$this->load->model('main_goods_model');

		$select = 'sub_goods_id, main_goods_id, attribute, image, search_code, number';
		$where = array('sub_goods_id'=>$sub_goods_id);
		$query = $this->db->select($select)->where($where)->get($this->TABLE);
		if ($query->num_rows() > 0)
		{
			$sub_goods = $query->row_array();
			$main_goods = $this->main_goods_model->get_one($sub_goods['main_goods_id']);
			if ($main_goods)
			{
				$goods = array(
					'main_goods'	=> $main_goods,
					'sub_goods'		=> $sub_goods
					);
				return $goods;
			}
			else
			{
				$this->error = $this->main_goods_model->error;
			}
		}
		else
		{
			$this->error = '不存在指定的子货物 ID:' . $sub_goods_id;	
		}
		return FALSE;
	}

	//更新库存
	public function update_stock($stock_type, $store_type, $sub_goods_id, $quantity)
	{
		$this->db->where('sub_goods_id', $sub_goods_id);
		if ('inbound' == $stock_type)
		{
			if ('1' == $store_type)
			{
				$this->db->set('stock', 'stock+'.$quantity, FALSE);
			}
			else if ('2' == $store_type)
			{
				$this->db->set('stock_unkown', 'stock_unkown+'.$quantity, FALSE);
			}
		}
		else if ('outbound' == $stock_type)
		{
			if ('1' == $store_type)
			{
				$this->db->set('stock', 'stock-'.$quantity, FALSE);
			}
			else if ('2' == $store_type)
			{
				$this->db->set('stock_unkown', 'stock_unkown-'.$quantity, FALSE);
			}
		}
		if (!$this->db->update($this->table))
		{
			$this->error = 'sub_goods_model::update_stock:277->SQL ERROR';
			return;
		}
	}

	//更新库存独立方法
	//sub_goods_id[@string] : 子货物的ID
	//quantity[@array{store_id[@number]=>quantity[@number]}] : 货物对应的各个仓库的库存
	//return : TRUE|FALSE
	public function change_stock($sub_goods_id, $quantities)
	{
		foreach ($quantities as $store_id => $quantity)
		{
			if (1 == $store_id)
			{
				$this->db->set('stock', 'stock+'.$quantity, FALSE);
			}
			else if (2 == $store_id)
			{
				$this->db->set('stock_unkown', 'stock_unkown+'.$quantity, FALSE);
			}
			else
			{
				$this->error = 'NO_EXSIT_STORE';
				return FALSE;
			}
		}
		$this->db->where('sub_goods_id', $sub_goods_id);
		if ($this->db->update($this->table))
		{
			return TRUE;
		}
		else
		{
			$this->error = 'UPDATE_STOCK_FAILED';
			return FALSE;
		}
	}

	//For ../libraris/MY_Form_validation.php
	public function form_validation($type, $value)
	{
		$this->load->model('Supplier_model');
		switch($type)
		{
			case 'is_supplier':
				$supplier_ids = explode('|', $value);
				foreach ($supplier_ids as $supplier_id)
				{
					if (!$this->Supplier_model->getOne($supplier_id))
					{
						return false;
					}
				}
				break;
			default:
				return false;
		}
		return true;
	}

	//格式化搜索结果
	private function format_result($sub_goods, $type='GROUP')
	{
		$this->load->Model('Main_goods_model');
		$arr = array();
		//已主货品集合格式返回
		if ('GROUP' === $type)
		{
			foreach ($sub_goods as $k=>$d)
			{
				if (isset($arr[$d->main_goods_id]))
				{
					array_push($arr[$d->main_goods_id]['sub_goods'], $d);
				}
				else
				{
					$main_goods = $this->Main_goods_model->getOne($d->main_goods_id);
					$arr[$d->main_goods_id] = array(
						'main_goods_id'	=> $d->main_goods_id,
						'main_number'	=> $main_goods['number'],
						'main_scode'	=> $main_goods['search_code'],
						'taobao_info'	=> $main_goods['taobao_info'],
						'sub_goods'		=> array()
						);
					array_push($arr[$d->main_goods_id]['sub_goods'], $d);
				}
			}
		}
		return $arr;
	} 

}